import json
import pandas as pd

def parse_json_extract_orders(jdata):
    orders_info = []

    # 提取 orderNumbers 和对应的 goodsNames
    for order in jdata.get('data', {}).get('cabinetOrderList', []):
        order_number = order.get('orderNumber')
        items = order.get('cabinetOrderItems', [])
        
        # 如果有多个商品项，则将它们的 goodsName 用分号隔开
        goods_names = '; '.join([item.get('goodsName', '') for item in items if 'goodsName' in item])

        orders_info.append({
            "OrderNumber": order_number,
            "GoodsNames": goods_names if goods_names else None
        })
    
    return orders_info

def write_to_excel(orders_info, excel_file_path):
    # 创建 DataFrame
    df = pd.DataFrame(orders_info)
    
    # 写入 Excel 文件
    df.to_excel(excel_file_path, index=False)

def order_json2excel(jdata, excel_path):
    orders_info = parse_json_extract_orders(jdata)
    # 写入 Excel 文件
    write_to_excel(orders_info, excel_path)

if __name__ == "__main__":
    input_json_file = "order.txt"  # 您的输入 JSON 文件路径
    output_excel = "order_numbers_with_goods.xlsx"  # 输出的 Excel 文件路径

    # 解析 JSON 并提取订单信息
    orders_info = parse_json_extract_orders(input_json_file)

    # 写入 Excel 文件
    write_to_excel(orders_info, output_excel)
 
    print(f"Orders and their goods have been successfully written to {output_excel}")
